<template>
  <div v-if="hasFormData" class="message-container user-message">
    <!-- 表单内容显示 -->
    <div class="message-content user-content">
      <div class="message-text user-text form-data-container">
        <div class="form-data-content">
          <div 
            v-for="(field, index) in formattedFields" 
            :key="index" 
            class="form-field"
          >
            <div class="field-label">{{ field.name }}:</div>
            
            <!-- 图片类型展示 -->
            <div v-if="field.isImage" class="field-value image-value">
              <div class="image-container">
                <img :src="field.value" :alt="field.name" @click="previewImage(field.value)" />
              </div>
            </div>
            
            <!-- 文件类型展示 -->
            <div v-else-if="field.isFile" class="field-value file-value">
              <a :href="field.value" target="_blank" class="file-link">
                <el-icon><Document /></el-icon>
                查看文件
              </a>
            </div>
            
            <!-- 多选值(数组)展示 -->
            <div v-else-if="field.isArray" class="field-value array-value">
              <el-tag 
                v-for="(item, i) in field.value" 
                :key="i"
                size="small"
                type="info"
                class="array-tag"
              >
                {{ item }}
              </el-tag>
            </div>
            
            <!-- 普通文本展示 -->
            <div v-else class="field-value text-value">
              {{ field.value }}
            </div>
          </div>
        </div>
      </div>
      <div class="message-time text-right">
        {{ formatTime(new Date()) }}
      </div>
    </div>
    
    <!-- 用户头像 -->
    <div class="message-avatar">
      <div class="user-avatar">
        <img v-if="userInfo?.avatar" :src="userInfo.avatar" alt="User" class="avatar-image">
        <span v-else>U</span>
      </div>
    </div>
    
    <!-- 图片预览 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="[previewUrl]"
      @close="closePreview"
    />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { Document } from '@element-plus/icons-vue';

// 获取用户信息
const { data: userInfo } = useAuth();

const props = defineProps({
  formConfig: {
    type: Object,
    default: () => ({})
  },
  inputs: {
    type: Object,
    default: () => ({})
  }
});

// 图片预览相关
const previewVisible = ref(false);
const previewUrl = ref('');

const previewImage = (url) => {
  previewUrl.value = url;
  previewVisible.value = true;
};

const closePreview = () => {
  console.log("%c Line:99 🍌 closePreview", "color:#b03734");
  previewVisible.value = false;
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  
  return `${hours}:${minutes}`;
};

// 判断是否为图片URL
const isImageUrl = (url) => {
  if (!url || typeof url !== 'string') return false;
  
  // 检查URL是否以图片扩展名结尾
  const extensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg', '.bmp'];
  const urlLower = url.toLowerCase();
  
  // 检查常见图片扩展名
  for (const ext of extensions) {
    if (urlLower.endsWith(ext)) return true;
  }
  
  // 检查是否包含图片处理参数
  if (urlLower.includes('x-oss-process=image') || 
      urlLower.includes('?imageMogr') || 
      urlLower.includes('?imageView')) {
    return true;
  }
  
  // 如果是对象且有type字段，检查是否为image类型
  if (typeof url === 'object' && url.type === 'image' && url.url) {
    return true;
  }
  
  return false;
};

// 是否有表单数据
const hasFormData = computed(() => {
  return Object.keys(props.inputs || {}).length > 0;
});

// 格式化表单数据，匹配字段名称和处理特殊类型
const formattedFields = computed(() => {
  if (!props.inputs || !props.formConfig) return [];
  
  let fields = [];
  let formFields = [];
  
  try {
    // 解析表单配置
    if (props.formConfig && typeof props.formConfig === 'string') {
      const config = JSON.parse(props.formConfig);
      if (config && config.form && Array.isArray(config.form.fields)) {
        formFields = config.form.fields;
      }
    } else if (props.formConfig && props.formConfig.form && Array.isArray(props.formConfig.form.fields)) {
      formFields = props.formConfig.form.fields;
    }
  } catch (error) {
    console.error('解析表单配置失败:', error);
  }
  
  // 处理每个输入字段
  for (const [key, value] of Object.entries(props.inputs)) {
    // 在表单配置中查找匹配的字段定义
    const fieldConfig = formFields.find(field => (field.prop === key || field.name === key));
    
    let fieldName = fieldConfig ? fieldConfig.name : key;
    let fieldValue = value;
    let isImage = false;
    let isFile = false;
    let isArray = Array.isArray(value);
    
    // 处理特殊格式的值
    if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
      // 处理图片对象格式 { type: 'image', url: 'xxx' }
      if (value.type === 'image' && value.remote_url) {
        fieldValue = value.remote_url;
        isImage = true;
      }
      // 处理其他可能的对象格式
      else if (value.value !== undefined) {
        fieldValue = value.value;
      }
    } else if (typeof value === 'string') {
      // 检查是否是图片URL
      isImage = isImageUrl(value);
      
      // 如果不是图片，检查是否是文件链接
      if (!isImage && (value.startsWith('http') || value.startsWith('https'))) {
        const fileExtensions = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.zip', '.rar'];
        const urlLower = value.toLowerCase();
        
        for (const ext of fileExtensions) {
          if (urlLower.endsWith(ext)) {
            isFile = true;
            break;
          }
        }
      }
    }
    
    fields.push({
      key,
      name: fieldName,
      value: fieldValue,
      isImage,
      isFile,
      isArray
    });
  }
  
  return fields;
});
</script>

<style lang="scss" scoped>
/* 复用ChatMessages中的基本样式 */
.message-container {
  display: flex;
  margin-bottom: 0.75rem;
}

.user-message {
  justify-content: flex-end;
  
  .message-avatar {
    margin-left: 8px;
  }
}

.message-avatar {
  flex-shrink: 0;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  overflow: hidden;
  background-color: #e9f5ff;
  color: #1890ff;
  
  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}



.user-content {
  text-align: right;
}

.message-text {
  display: inline-block;
  padding: 8px 12px;
  border-radius: 8px;
  white-space: pre-wrap;
  word-break: break-word;
  text-align: left;
}

.user-text {
  background-color: #1890ff;
  color: white;
  border-top-right-radius: 2px;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 2px;
}

.text-right {
  text-align: right;
}

/* 表单数据特有样式 */
.form-data-container {
  min-width: 250px;
}

.form-data-content {
  .form-field {
    display: flex;
    margin-bottom: 6px;
    align-items: flex-start;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .field-label {
    font-weight: 500;
    color: rgba(255, 255, 255, 0.8);
    flex-shrink: 0;
    
    padding-right: 8px;
  }
  
  .field-value {
    flex-grow: 1;
    color: white;
    word-break: break-word;
    
    &.image-value {
      .image-container {
        width: 70px;
        height: 70px;
        border-radius: 4px;
        overflow: hidden;
        cursor: pointer;
        border: 1px solid rgba(255, 255, 255, 0.3);
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          display: block;
        }
      }
    }
    
    &.file-value {
      .file-link {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 8px;
        background-color: rgba(255, 255, 255, 0.2);
        border-radius: 4px;
        color: white;
        text-decoration: none;
        font-size: 12px;
        
        &:hover {
          background-color: rgba(255, 255, 255, 0.3);
        }
      }
    }
    
    &.array-value {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
      
      .array-tag {
        background-color: rgba(255, 255, 255, 0.2);
        color: white;
        border: none;
      }
    }
    
    &.text-value {
      line-height: 1.4;
    }
  }
}
</style>